package com.example.rwq_test.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 找出数组中两数之和等于目标值的一组数据的下角标
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2023/9/4
 */
public class TwoNumEqualsTarget {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 3, 4, 5};
        int[] ints = twoSum(arr, 10);
        Arrays.stream(ints).forEach(System.out::print);
    }

    private static int[] twoSum(int[] arr, int tar) {
        if (arr == null || arr.length < 2) {
            throw new ArithmeticException("arr length too small.");
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            if (map.containsKey(tar - arr[i])) {
                return new int[]{i, map.get(tar - arr[i])};
            }
            map.put(arr[i], i);
        }
        throw new IllegalArgumentException("no two sum solution.");
    }
}
